package org.robert.export_client.aop;

import com.alibaba.fastjson.JSON;
import org.robert.export_client.excel.metadata.IBaseExcelJson;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * ExcelJsonAdapter: 降属性中的ExcelJson注解字段解析为Object
 *
 * @author zhaoshengtao
 * @date 2024/01/19
 */
public class ExcelJsonAdapter {


    public <T extends IBaseExcelJson> T parseJsonToObject(String json, Class<T> clazz) throws Exception {
        return JSON.parseObject(json, clazz);
    }

    public Map<String, Object> extractFieldValues(Object entity) throws Exception {
        Map<String, Object> fieldValues = new HashMap<>();
        for (Field field : entity.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(ExcelJson.class)) {
                ExcelJson annotation = field.getAnnotation(ExcelJson.class);
                Object fieldValue = field.get(entity);
                if (fieldValue != null) {
                    Class<? extends IBaseExcelJson> targetClass = annotation.parserFor();
                    IBaseExcelJson parsedEntity = parseJsonToObject((String) fieldValue, targetClass);
                    for (Field subField : targetClass.getDeclaredFields()) {
                        subField.setAccessible(true);
                        fieldValues.put(field.getName() + "_" + subField.getName(), subField.get(parsedEntity));
                    }
                }
            } else {
                fieldValues.put(field.getName(), field.get(entity));
            }
        }
        return fieldValues;
    }


}
